# -*- coding: UTF-8 -*-
import sys
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, session,Blueprint
import os
from log import Logger
import conf_parser
import queue
import json
data = Blueprint('data', __name__)

q=queue.Queue()
w=queue.Queue()

@data.route('/setData', methods=['POST'])
def show_data():
    rs = request.json;
    v = json.dumps(rs,ensure_ascii=False);
    q.put(v)
    print("收到客户端数据："+v)
    return str("OK")

@data.route('/getData', methods=['POST'])
def getData():
    if q.qsize()==0:
        print("没有客户端数据")
        return str("Fail")
    v = q.get();
    print("发送客户端数据：" + v)
    return str(v)

@data.route('/setServerData', methods=['POST'])
def show_writeData():
    rs = request.json;
    v = json.dumps(rs,ensure_ascii=False);
    q.put(v)
    print("收到服务端数据："+v)
    return str("OK")

@data.route('/getServerData', methods=['POST'])
def getWriteData():
    if q.qsize()==0:
        print("没有服务端数据")
        return str("Fail")
    v = q.get();
    print("发送服务端数据：" + v)
    return str(v)

@data.route('/upload', methods=['POST'])
def upload():
    try:
        upload_file = request.files['file']
        receive_file = upload_file.filename
        filepath = resource_path('filepath/log')
        isExists = os.path.exists(filepath)
        if not isExists:
            os.makedirs(filepath)
        filepath = resource_path('filepath/image')
        isExists = os.path.exists(filepath)
        if not isExists:
            os.makedirs(filepath)
        log = Logger(resource_path('filepath/log/all.log'), level='info')
        log.logger.info('接收到图片:' + receive_file)
        if upload_file:
            upload_file.save(resource_path('filepath/image/'+receive_file))
    except Exception as e:
        log.logger.error('上传失败:' + e)
    return str("OK")

def resource_path(relative_path):
    base_path = conf_parser.getValue('server', 'file_path')
    return os.path.join(base_path, relative_path)
